<template>
  <div class="app-container">
    <div class="filter-box">
      <el-button type="primary" size="small" @click="handleAdd">新增角色</el-button>
    </div>
    <!-- 数据列表 -->
    <el-table :data="tableData" border style="width: 100%;">
      <el-table-column prop="name" label="角色名称" align="center" />
      <el-table-column prop="description" label="描述" align="center" />
      <el-table-column prop="slug" label="标识" align="center" />
      <el-table-column prop="created_at" label="创建日期" align="center" />
      <el-table-column prop="updated_at" label="修改时间" align="center" />
      <el-table-column label="操作" width="180" align="center">
        <template slot-scope="scope">
          <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">修改</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="listQuery.page"
      :limit.sync="listQuery.pageSize"
      @pagination="getTableData"
    />

    <!-- 新增/编辑 弹窗 -->
    <el-dialog
      :title="type"
      :visible.sync="dialogFormVisible"
      :destroy-on-close="true"
      @closed="handleClose"
      @opened="handleOpen"
    >
      <el-form ref="roleForm" :model="roleForm">
        <el-form-item label="名称" label-width="120px">
          <el-input v-model="roleForm.name" autocomplete="off" placeholder="请输入角色名称" />
        </el-form-item>
        <el-form-item label="描述" label-width="120px">
          <el-input v-model="roleForm.description" autocomplete="off" placeholder="请输入角色描述" />
        </el-form-item>
        <el-form-item label="标签" label-width="120px">
          <el-input v-model="roleForm.slug" autocomplete="off" placeholder="请输入角色标签" />
        </el-form-item>
        <el-form-item label="菜单权限" label-width="120px">
          <el-tree
            ref="menuTree"
            :data="menuList"
            :props="defaultProps"
            node-key="id"
            show-checkbox
          />
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="handleConfirm">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>
<script>
import { addRole, delRole, listRole, updateRole, getRole } from '@/api/system/role'
import { getMenus } from '@/api/system/menu'
import Pagination from '@/components/Pagination'
export default {
  components: { Pagination },
  data() {
    return {
      menuList: [],
      defaultProps: {
        children: 'children',
        label: 'title'
      },
      tableData: [],
      dialogFormVisible: false,
      type: '',
      roleForm: {
        name: '',
        description: '',
        slug: '',
        menuId: ''
      },
      options: [{
        value: '管理员',
        label: '管理员'
      }],
      total: 0,
      listQuery: {
        page: 1,
        pageSize: 20
      }
    }
  },
  created() {
    this.getTableData()
  },
  methods: {
    getTableData() {
      listRole(this.listQuery).then(res => {
        this.tableData = res.data.list
        this.total = res.data.total
      })
    },
    handleClose() {
      this.$refs.roleForm.resetFields()
      this.roleForm = {
        name: '',
        description: '',
        slug: '',
        menuId: '',
        permissions: []
      }
    },
    handleOpen() {
      if (this.type === '修改角色') {
        const menuIds = []
        this.roleForm.menu_ids.forEach(element => {
          menuIds.push(Number(element))
        })
        console.log(menuIds)
        this.$refs.menuTree.setCheckedKeys(menuIds)
      }
    },
    getMenuList() {
      return new Promise((resolve, reject) => {
        if (this.menuList.length === 0) {
          getMenus().then(res => {
            this.menuList = res.data
            resolve('ok')
          }).catch(e => {
            reject(e)
          })
        }
        resolve('ok')
      })
    },
    async handleAdd() {
      await this.getMenuList()
      this.type = '新增角色'
      this.dialogFormVisible = true
    },
    async handleEdit(index, row) {
      await this.getMenuList()
      const { data } = await getRole(row.id)
      this.type = '修改角色'
      this.roleForm = data.info
      this.dialogFormVisible = true
    },
    handleDelete(index, row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        delRole(row.id).then(res => {
          this.$message({
            type: 'success',
            message: '删除成功!'
          })
          this.getTableData()
        }).catch(e => {
          this.$message({
            type: 'error',
            message: '删除失败!'
          })
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        })
      })
    },
    // 新增或修改 角色
    handleConfirm() {
      const menuList = []
      this.$refs.menuTree.getCheckedNodes().forEach(element => {
        menuList.push(element.id)
      })
      this.roleForm.menuIds = menuList.join(',')
      const { description, name, slug, menuIds } = this.roleForm
      if (this.type === '新增角色') {
        addRole({ description, name, slug, menuIds }).then(res => {
          this.$message({
            message: '新增成功!',
            type: 'success'
          })
          this.getTableData()
          this.dialogFormVisible = false
        }).catch(e => {
          this.$message({
            message: '新增失败!',
            type: 'error'
          })
          this.dialogFormVisible = false
        })
      } else {
        updateRole(this.roleForm.id, { description, name, slug, menuIds }).then(res => {
          this.$message({
            message: '修改成功!',
            type: 'success'
          })
          this.getTableData()
          this.dialogFormVisible = false
        }).catch(e => {
          this.$message({
            message: '修改失败!',
            type: 'error'
          })
          this.dialogFormVisible = false
        })
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.app-container {
  padding: 20px;
  .filter-box {
    margin-bottom: 20px;
    .filter-item {
      font-size: 14px;
      span {
        margin-right: 10px;
      }
    }
  }
}
</style>
